package com.leyou.item.web;

import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("brand")
public class BrandController {

    private final BrandService brandService;

    public BrandController(BrandService brandService) {
        this.brandService = brandService;
    }

    /**
     * 根据id查询品牌
     *
     * @param id id
     * @return 返回品牌
     */
    @GetMapping("/{id}")
    public ResponseEntity<BrandDTO> queryById(@PathVariable("id") Long id) {
        //查询
        Brand brand = brandService.getById(id);
        //转换
        BrandDTO brandDTO = new BrandDTO(brand);
        //返回
        return ResponseEntity.ok(brandDTO);
    }

    /**
     * 根据id集合查询品牌集合
     *
     * @param ids id集合
     * @return 品牌集合
     */
    @GetMapping("/list")
    public ResponseEntity<List<BrandDTO>> queryBrandByIds(@RequestParam("ids") List<Long> ids) {
        //查询
        List<Brand> brands = brandService.listByIds(ids);
        //转换
        List<BrandDTO> dtoList = brands.stream().map(BrandDTO::new).collect(Collectors.toList());
        //返回
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据分类id查询品牌
     * @param categoryId  分类 id
     * @return  品牌
     */
    @GetMapping("/of/category")
    public ResponseEntity<List<BrandDTO>> queryBrandByCategoryId(@RequestParam("id") Long categoryId) {
        List<BrandDTO> dtoList = brandService.queryBrandByCategoryId(categoryId);
        return ResponseEntity.ok(dtoList);
    }

    /**
     *   根据分页查询品牌
     * @param key  搜索关键字
     * @param page  页码
     * @param rows  每页大小
     * @return  返回结果
     */
    @GetMapping("/page")
    public ResponseEntity<PageDTO<BrandDTO>> queryByPage
            (@RequestParam(value = "key",required = false) String key,
             @RequestParam(value = "page",defaultValue = "1") Integer page,
             @RequestParam(value = "rows",defaultValue = "5") Integer rows ){
        PageDTO<BrandDTO> dto = brandService.queryByPage(key,page,rows);
        return ResponseEntity.ok(dto);
    }

    /**
     *  新增品牌
     * @param brandDTO   品牌信息
     * @return  无
     */
    @PostMapping
    public ResponseEntity<Void> saveBrand(BrandDTO brandDTO){
        //新增
        brandService.saveBrand(brandDTO);
        //返回结果 201
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
}